<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <strong style="font-size: 20px;">
          员工收入汇总
        </strong>
      </el-col>
      <el-col :span="20" align="right">
        <span style="margin-right: .5em">
          <el-select
            v-model="store"
            style="width: 150px;"
            placeholder="门店"
            filterable
            @change="filterGenerate();dataProcessor()"
          >
            <el-option
              v-for="item in stores"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="date"
            type="month"
            @change="filterGenerate();dataProcessor()"
          />
          <!-- <el-date-picker
            v-model="search.date"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy/MM/dd HH:mm:ss"
            :editable="false"
            :clearable="false"
            @change="filterGenerate();dataProcessor()"
          /> -->
        </span>
        <span style="margin-right: .5em">
          <el-button size="medium" type="primary" icon="el-icon-plus" plain @click="totalExport()">
            导出
          </el-button>
        </span>
      </el-col>
    </el-row>

    <el-row>
      <el-table
        v-loading="loading"
        :data="list"
        element-loading-text="加载中..."
        fit
        lazy
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="#" type="index" />
        <el-table-column prop="name" label="员工" />
        <el-table-column prop="id" label="员工工号" />
        <el-table-column prop="phone" label="用户" />
        <el-table-column prop="outAcntNm" label="真实姓名" />
        <el-table-column prop="licNo" label="身份证" />
        <el-table-column prop="amount" label="金额" />
      </el-table>
    </el-row>
  </div>
</template>

<script>
import exportExcelCsv from '@/utils/exportExcelCsv'
export default {
  data() {
    return {
      loading: false,
      list: [],
      date: [],
      stores: [],
      store: 0
    }
  },
  created() {
    const now = new Date() // 当前时间
    const month = now.getTime() - (86400000 * 30)
    const date = new Date(month)
    const startDate = `${date.getFullYear()}/${date.getMonth() + 1}` // 拼接成yyyy-mm-dd格式
    console.log(startDate)
    // const endDate = `${year}/${month + 1}/01 00:00:00`
    this.date = startDate
    this.getStores()
  },
  methods: {
    getStores() {
      this.axios.get(`/manage/stores`, {
        params: {
          '@filter': `entity.getStatus() == "0"`,
          limit: 10000000
        }
      }).then(res => {
        if (res.data.length > 0) {
          this.stores = res.data
          this.store = res.data[0].id
          this.filterGenerate()
          this.dataProcessor()
        }
      })
    },
    filterGenerate() {
      this.filter = {
        '@filter': `(entity.getProfitType() >= 8 && entity.getProfitType() <= 10)`,
        '@select': 'SUM(entity.amount) as amount, entity.user.id as userId, entity.user.username as phone, entity.staff.name as name',
        '@groupBy': 'entity.user.id',
        'limit': 100000000
      }
      if (this.store) {
        this.filter['@filter'] += ` && entity.getSettle().getOrderItem().getOrder().getStore().getId() == '${this.store}'`
      }
      if (this.date) {
        console.log(this.date)
        const date = new Date(this.date)
        const startTime = `${date.getFullYear()}/${date.getMonth() + 1}/01 00:00:00`
        // const endDate = date.getTime() + 86400000 * 30
        const endTime = `${date.getFullYear()}/${date.getMonth() + 1}/31 23:59:59`
        this.filter['@filter'] += ` && entity.getCreatedTime() >= datetime.get('${startTime}') && entity.getCreatedTime() < datetime.get('${endTime}')`
      }
    },
    dataProcessor() {
      this.loading = true
      const promise = []
      let list = []
      let accounts = []

      // table数据
      promise.push(
        this.axios.get(`/manage/settle-items`, {
          params: {
            '@filter': this.filter['@filter'],
            '@select': 'SUM(entity.amount) as amount, entity.user.id as userId, entity.user.username as phone, entity.staff.name as name, entity.staff.id as id',
            '@groupBy': 'entity.user.id',
            'limit': 100000000
          }
        }).then(res => {
          list = res.data
        })
      )

      promise.push(
        this.axios.get(`/manage/fuiou-accounts`, {
          params: { 'limit': 100000000 }
        }).then(res => {
          accounts = res.data
        })
      )

      Promise.all(promise).then(res => {
        list.map(v => {
          const account = accounts.find(w => w.user?.id === v.userId)
          if (account) {
            v.outAcntNo = account.outAcntNo
            v.licNo = account.licNo + '\t'
            v.outAcntNm = account.outAcntNm
          } else {
            v.outAcntNo = ''
            v.licNo = ''
            v.outAcntNm = ''
          }
        })
        this.loading = false
        this.list = list
        console.log('list', list)
      })
    },
    totalExport() {
      // table数据
      const list = JSON.parse(JSON.stringify(this.list))
      if (list.length === 0) {
        this.$message.error('暂无导出数据')
        return
      }
      const label = {
        'name': '员工',
        'id': '工号',
        'phone': '用户',
        'outAcntNm': '真实姓名',
        'licNo': '身份证',
        'amount': '金额'
      }
      let storeName = '未知门店'
      for (const i of this.stores) {
        if (i.id == this.store) {
          storeName = i.name
        }
      }
      const date = new Date(this.date)
      exportExcelCsv(label, list, `${storeName}${date.getFullYear()}年${date.getMonth() + 1}月工资收入.csv`)
    }
  }
}
</script>
